<?php

namespace App\Http\Controllers;

use App\Image;
use GuzzleHttp;
use Illuminate\Http\Request;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;

class ImageController extends Controller
{

    protected $qnAuth;
    protected $bucketMgr;

    public function __construct()
    {
        $this->middleware(['auth', 'admin'], ['except' => ['squareImage', 'getCloudImages', 'callBack']]);

        $accessKey = config('app.QN_accessKey');
        $secretKey = config('app.QN_secretKey');
        $this->qnAuth = new Auth($accessKey, $secretKey);
        $this->bucketMgr = new BucketManager($this->qnAuth);

    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $images = Image::orderBy('created_at','desc')->paginate(20);
        return view('image.index',compact('images'));

    }
    public function qiniuIndex()
    {

// http://developer.qiniu.com/docs/v6/api/reference/rs/list.html#list-description
// 要列取的空间名称
        $bucket = config('app.QN_bucketName');

// 要列取文件的公共前缀
        $prefix = '';

// 上次列举返回的位置标记，作为本次列举的起点信息。
        $marker = '';

// 本次列举的条目数
        $limit = 1000;


// 列举文件
        list($iterms, $marker, $err) = $this->bucketMgr->listFiles($bucket, $prefix, $marker, $limit);
        if ($err !== null) {
            echo "\n====> list file err: \n";
            var_dump($err);
        } else {
        }
        $collectionQiniuImages = collect(array_pluck($iterms,['key']));
        $dbImages = Image::all()->pluck(['key']);
        //qiniu has the db have not
        $qiniuHasTheDbNots = $collectionQiniuImages->diff($dbImages);
        //需要删除七牛的图片
        //删除多远的七牛照片
        //当数据库照片删除的时候
        //七牛没有删除照片就在这里执行任务
        foreach ($qiniuHasTheDbNots as $toDelete) {
            $this->bucketMgr->delete($bucket, $toDelete);
        }

        //image 数据库中有 七牛没有 需要去重新取图片
        $dbHasQiniuHasNot = $dbImages->diff($collectionQiniuImages);
        //todo:有机会让这一步照片自动生成
        //todo:一行命令删除 没有照片或者引用过的图片


        return view('image.qiniuIndex',compact('iterms'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $bucket = config('app.QN_bucketName');

        //http://developer.qiniu.com/article/developer/security/put-policy.html

        $policy = array(
            'returnUrl' => route('image.index'),
            'callbackUrl'=>'http://115.28.94.157/image/callback',
            'callbackBody'=>'fname=$(fname)&fsize=$(fsize)&bucket=$(bucket)&key=$(key)&etag=$(etag)&description=$(x:description)&mimeType=$(mimeType)&imageInfo=$(imageInfo)&exif=$(exif)'
        );
        //设置application/json格式回调

        $upToken = $this->qnAuth->uploadToken($bucket, null, 3600, $policy);

        $jsUpToken = $this->qnAuth->uploadToken($bucket, null, 3600);

        return view('image/create',compact('upToken','jsUpToken'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Image $image)
    {
        $bucket = config('app.QN_bucketName');
        $policy = array(
            'returnUrl' => route('image.edit',[$image]),
        );
        $upToken = $this->qnAuth->uploadToken($bucket, null, 3600, $policy);

        return view('image.edit',compact('image','upToken'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Image $image)
    {
        $image->description = $request->input('description');
        $image->save();
        return redirect(route('image.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $res = Image::destroy($id);
        $message = $res ? 'success' : 'error';
        return response()->json(['status' => $res, 'message' => $message]);
    }

    public function callBack(Request $request)
    {
//获取回调的body信息
        $callbackBody = file_get_contents('php://input');

//回调的contentType
        $contentType = 'application/x-www-form-urlencoded';

//回调的签名信息，可以验证该回调是否来自七牛
        $authorization = $_SERVER['HTTP_AUTHORIZATION'];

//七牛回调的url，具体可以参考：http://developer.qiniu.com/docs/v6/api/reference/security/put-policy.html
        $url = 'http://www.trytv.org/image/callback';
        $isQiniuCallback = $this->qnAuth->verifyCallback($contentType, $authorization, $url, $callbackBody);
        if ($isQiniuCallback) {
            $image = Image::firstOrNew(['key'=>trim($request->input('key'))]);
            $image->bucket=trim($request->input('bucket'));
            $image->description=trim($request->input('description'));
            $image->fname=trim($request->input('fname'));
            $image->fsize=trim($request->input('fsize'));
            $image->format=trim($request->input('mimeType'));
            $image->save();
            $resp = array('ret' => '添加到数据库成功');
        } else {
            $resp = array('ret' =>' 失败');
        }

        return json_encode($resp);
    }

    public function fetchImageBy(Request $request) {
        $url = $request->input('url');
        $bucket = config('app.QN_bucketName');
        $key = time();
        list($ret, $err) = $this->bucketMgr->fetch($url, $bucket, $key);
        if ($err !== null) {
            $request->session()->flash('error', $err);
        } else {
            $image = Image::firstOrNew(['key'=>$key]);
            $image->mimeType = $ret['mimeType'];
            $image->fsize = $ret['fsize'];
            $image->fname= $url;
            $image->description=$request->input('description');
            $image->bucket = $bucket;
            $image->save();
            return redirect(route('image.index'));
        }

    }

    public function removeRedandantImages() {
        $cloudImageCollection = collect($this->getCloudImages())->pluck('key');
        $localImageCollection = Image::all()->pluck('key');
        dd($localImageCollection,$cloudImageCollection);



    }


    protected function getCloudImages() {

        $bucket = config('app.QN_bucketName');

        // 要列取文件的公共前缀
        $prefix = '';

// 上次列举返回的位置标记，作为本次列举的起点信息。
        $marker = '';

// 本次列举的条目数
        $limit = 1000;
        list($iterms, $marker, $err) = $this->bucketMgr->listFiles($bucket, '', $marker, $limit);
        if ($err !== null) {
            echo "\n====> list file err: \n";
            dd($err);
        } else {
            //echo "Marker: $marker\n";
            //echo "\nList Iterms====>\n";
            return $iterms;
        }
    }

    public function squareImage($size=300) {
        $waterMaker = 'imageView2/1/w/'.$size.'/h/'.$size;
        $baseUrl = 'http://img.trytv.org';
        return $baseUrl.'/'.$this->key.'?'.$waterMaker;
    }


    public function fixImageAltDescription() {
        $images = Image::all();
        foreach($images as $image) {
            if(!str_contains($image->description,'http://')) {
                continue;
            }
            $movie = $image->movies->first();
            $show = $image->shows->first();
            $article = $image->article;
            if ($article) {
                $image->description =  $article->title;
                $image->save();
            }

            if($show) {
                $image->description =  $show->full_name;
                $image->save();
            }
            if($movie) {
                $image->description =  $movie->full_name;
                $image->save();
            }
        }
    }


    public function getImagesSizeInfo() {
        $images = Image::where('height','0')->get();



        $webURl = 'http://www.ttmeiju.com';
        $client = new GuzzleHttp\Client();
        $header = [
            'Host'=>'img.trytv.org',
            'Accept'=>'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding'=>'gzip, deflate, sdch',
            'Accept-Language'=>'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
            'Cache-control:'=>'max-age=0',
            'Dnt'=>'1',
            'Referer'=>'https://www.baidu.com/link?url=OOIVn0qbApPkoe99TFbeGI307BTpCTY4pXGJcll69PEQRzlZjqbxMmnq9DoI3AWQ&wd=&eqid=fe299461002fe7600000000557314a9e',
            'Upgrade-Insecure-Requests'=>'1',
            'User-Agent'=>'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',
        ];
        $baseUrl = '7xss6j.com2.z0.glb.clouddn.com';


        foreach($images as $image) {
            sleep(1);
            $url=  $baseUrl.'/'.$image->key.'?imageInfo';
            $res = $client->request('GET', $webURl, ['headers' => $header]);
            $content = $res->getBody()->getContents();
            $jsonArray = json_decode($content,true);
            $image->fill($jsonArray);
            $image->save();
        }



    }

    public function imageQuote(){
        $quotes = Image::where('key','like','%brainyquote%')->paginate(15);
        return view('image.imageQuote',compact('quotes'));
    }


    public function ueditorImageList()
    {
        $article_id = 0;
        $show_id = 0;
        $keyword = '';


    }


}
